import React from 'react';
import weAjax from '../utils/ajax';
import './login.css'





class Login extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange1 = this.handleChange1.bind(this);
        this.handleChange2 = this.handleChange2.bind(this);
        this.state = {
            userid: '',
            userpw: ''
        };
        this.onSubmit = this.onSubmit.bind(this);
        this.onSubmit2 = this.onSubmit2.bind(this);
    }
    // 登陆
    login = () => {
        weAjax({ url: '/admin/login', method: 'post', data: { userid: this.state.userid, userpw: this.state.userpw } }, (data) => {
            if (data.code) {
                var userinfo = data.data;
                localStorage.setItem('USERINFO', JSON.stringify(userinfo));
                this.props.onLogin();
                console.log('成功登陆!');
            } else {
                alert(data.data);
            }
        })
    }

    // 点击执行登陆
    onSubmit(e) {
        e.preventDefault();
        this.login();
    }
    // 回车执行登陆
    onSubmit2(e) {
        if (e.key === 'Enter') {
            this.login();
        }
    }

    handleChange1(e) {
        this.setState({ userid: e.target.value });
    }

    handleChange2(e) {
        this.setState({ userpw: e.target.value });
    }

    render() {
        const userid = this.state.userid;
        const userpw = this.state.userpw;
        // 如果登陆过（在有效期内），直接跳转到首页

        return (
            <div className='mask' ref='login'>
                <div className="form-form login-form" >
                    <div className="form-title">用户登陆</div>
                    <input className="form-input" value={userid} onChange={this.handleChange1} placeholder="用户名" autoFocus />
                    <input className="form-input" value={userpw} onChange={this.handleChange2} onKeyDown={this.onSubmit2} placeholder="密码" />
                    <button onClick={this.onSubmit} className='form-button'>登 录</button>
                    <div className="b2">
                        {/*<a className='new-user'>新用户</a>*/}
                        <a href="/register" className='forget-pw'>忘记密码</a>
                    </div>
                </div>

            </div>
        );

    }
}

export default Login;